package cn.sirun.com.fca.map.view.impl;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tencent.cloud.iov.flow.presenter.IPresenter;
import com.tencent.cloud.iov.flow.view.IContentViewContainer;
import com.tencent.cloud.iov.kernel.model.BaseResponse;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ActivityUtils;
import com.tencent.cloud.iov.util.storage.TXSharedPreferencesUtils;
import com.tencent.cloud.uikit.utils.DialogUtils;
import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.BaseObject;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.Location;
import com.tencent.lbssearch.object.param.SearchParam;
import com.tencent.lbssearch.object.param.SuggestionParam;
import com.tencent.lbssearch.object.result.SearchResultObject;
import com.tencent.lbssearch.object.result.SuggestionResultObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.sirun.com.fca.map.R;
import cn.sirun.com.fca.map.adapter.InventoryAdapter;
import cn.sirun.com.fca.map.adapter.PoiResultAdapter;
import cn.sirun.com.fca.map.adapter.SearchResultAdapter;
import cn.sirun.com.fca.map.constant.MapActivityConst;
import cn.sirun.com.fca.map.listener.MyItemLongClickListener;
import cn.sirun.com.fca.map.model.SearchResultData;
import cn.sirun.com.fca.map.model.bean.AddressBean;
import cn.sirun.com.fca.map.model.repose.MapCarLocation;
import cn.sirun.com.fca.map.model.repose.MapCollectedResponse;
import cn.sirun.com.fca.map.model.repose.MapHomeCompanyResponse;
import cn.sirun.com.fca.map.presenter.IMapPresenter;
import cn.sirun.com.fca.map.presenter.impl.MapPresenter;
import cn.sirun.com.fca.map.uitl.AddressHistoryUtils;
import cn.sirun.com.fca.map.view.IMapCollectedView;
import cn.sirun.com.fca.map.view.impl.MapBaseLoadingFlowView;
import cn.sirun.com.fca.map.widget.SlideRecyclerView;

import static android.content.Context.MODE_PRIVATE;


public class MapSearchHistoryView extends MapBaseLoadingFlowView<IMapPresenter> implements IMapCollectedView,View.OnClickListener{

    private SlideRecyclerView lvdata;
    private InventoryAdapter searchResultAdapter;
    private TextView tvtocollect;
    private TextView tvhome;
    private TextView tvcompany;
    private TextView tvgsstation;
    private TextView tvcharge;
    private TextView tvcate;
    private TextView tvhotel;
    private LinearLayout ll_home_address;
    private LinearLayout ll_company_address;
    private ImageView iv_goback;
    private ImageView iv_textclear;
    private ImageView iv_glass;
    private List<AddressBean> listAddress;
    private EditText et_search;
    private RecyclerView lvSearchData;
    private AddressBean addressBean;
    private AddressBean homeAddress;
    private AddressBean companyAddress;
    private String flg;
    private String din;
    private PoiResultAdapter poiResultAdapter;


    public MapSearchHistoryView(Activity activity) {
        super(activity);
    }

    public MapSearchHistoryView(Activity activity, IContentViewContainer container) {
        super(activity, container);

    }
    @Override
    public void onCreate() {
        super.onCreate();

        View view = LayoutInflater.from(getContext())
                .inflate(R.layout.map_search_history_fragment, null, false);
        setContentView(view);
        lvdata = view.findViewById(R.id.lv_map_result_history);
        lvdata.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        DividerItemDecoration itemDecoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.divider_inset));
        lvdata.addItemDecoration(itemDecoration);

        listAddress = AddressHistoryUtils.getAddressHistoty();

        if(listAddress==null){
            lvdata.setVisibility(View.GONE);
        } else{
            lvdata.setVisibility(View.VISIBLE);
            Collections.reverse(listAddress);
            searchResultAdapter=new InventoryAdapter(getContext(),listAddress);
            //点击查看
            searchResultAdapter.setItemClickLister(new InventoryAdapter.OnItemClickLister() {
                @Override
                public void onItemClickLister(View view, int position) {
                    Intent intent = Router.fromPath(MapActivityConst.Path.MAP_SEND_CAR);
                    if(flg.equals("modifyhome")){
                        intent.putExtra("set","sethome");
                    }else if(flg.equals("modifycompany")){
                        intent.putExtra("set","setcompany");
                    } else {
                        intent.putExtra("set","send");
                    }
                    intent.putExtra("addresslat",listAddress.get(position).getLatitude()+"");
                    intent.putExtra("addresslng",listAddress.get(position).getLongitude()+"");
                    intent.putExtra("title",listAddress.get(position).getName());
                    intent.putExtra("address",listAddress.get(position).getAddress());
                    ActivityUtils.startActivity(getActivity(),intent);
                }
            });
            //删除操作
            searchResultAdapter.setOnDeleteClickListener(new InventoryAdapter.OnDeleteClickLister() {
                @Override
                public void onDeleteClick(View view, int position) {
                    listAddress.remove(position);
                    AddressHistoryUtils.saveAddressHistory(listAddress);
                    searchResultAdapter.notifyDataSetChanged();
                    lvdata.closeMenu();
                }
            });
            lvdata.setAdapter(searchResultAdapter);
        }

//进一步搜索页面
        iv_textclear = view.findViewById(R.id.iv_map_search_close);
        iv_textclear.setOnClickListener(this);
        iv_glass = view.findViewById(R.id.iv_map_search_glass);
        iv_glass.setOnClickListener(this);
        et_search = view.findViewById(R.id.et_map_to_search);
        et_search.setOnClickListener(this);
        et_search.addTextChangedListener(textWatcher);
        lvSearchData = view.findViewById(R.id.lv_map_result);
        lvSearchData.setLayoutManager(new LinearLayoutManager(getContext(),
                LinearLayoutManager.VERTICAL, false));
//收藏夹
        tvtocollect = view.findViewById(R.id.tv_map_search_collect);
        tvtocollect.setOnClickListener(this);
//家公司地址
        tvhome = view.findViewById(R.id.tv_map_collected_homeaddress);
        tvcompany = view.findViewById(R.id.tv_map_collected_company_address);
//加油站
        tvgsstation = view.findViewById(R.id.tv_map_search_gasstation);
        tvgsstation.setOnClickListener(this);

        tvcharge = view.findViewById(R.id.tv_map_search_charge);
        tvcharge.setOnClickListener(this);

        tvcate = view.findViewById(R.id.tv_map_search_cate);
        tvcate.setOnClickListener(this);

        tvhotel = view.findViewById(R.id.tv_map_search_hotel);
        tvhotel.setOnClickListener(this);
        //添加家地址
        ll_home_address = view.findViewById(R.id.ll_map_home_address);
        ll_home_address.setOnClickListener(this);
        //添加公司地址
        ll_company_address = view.findViewById(R.id.ll_map_company_address);
        ll_company_address.setOnClickListener(this);

        iv_goback = view.findViewById(R.id.iv_map_search_go_back);
        iv_goback.setOnClickListener(this);

        din=TXSharedPreferencesUtils.getValue("car_activate_info");
        if(!TextUtils.isEmpty(din)) {
            getPresenter().getHomeAddress(din);
        }else {
            getPresenter().getHomeAddress("");
        }
        // 获取意图对象获取传递的值
        Intent intent = getActivity().getIntent();
        flg = intent.getStringExtra("set");
        if(TextUtils.isEmpty(flg)){
            flg="set";
        }
        Log.e("eee",flg+"---");
    }

    final TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            searchPoi(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    };
    /**
     * poi检索
     */
    protected void searchPoi(String keyword) {
        TencentSearch tencentSearch = new TencentSearch(getContext());
        String keyWord = keyword;
        //城市搜索
        SearchParam.Region region = new SearchParam.Region().poi("北京").//设置搜索城市
                autoExtend(false);//设置搜索范围不扩大
        //圆形范围搜索
        Location location1 = new Location().lat(39.984154f).lng(116.307490f);
        SearchParam.Nearby nearBy = new SearchParam.Nearby().point(location1).r(1000);
        //矩形搜索，这里的范围是故宫
        Location location2 = new Location().lat(39.913127f).lng(116.392164f);
        Location location3 = new Location().lat(39.923034f).lng(116.402078f);
        SearchParam.Rectangle rectangle = new SearchParam.Rectangle().point(location2, location3);

        //filter()方法可以设置过滤类别，
        //search接口还提供了排序方式、返回条目数、返回页码具体用法见文档，
        //同时也可以参考官网的webservice对应接口的说明
        SearchParam searchParam = new SearchParam().keyword(keyWord).boundary(region);
        tencentSearch.search(searchParam, new HttpResponseListener() {

            @Override
            public void onFailure(int arg0, String arg1, Throwable arg2) {
                // TODO Auto-generated method stub
//                printResult(arg1);
            }

            @Override
            public void onSuccess(int arg0, BaseObject arg1) {
                // TODO Auto-generated method stub
                if (arg1 == null) {
                    return;
                }
                SearchResultObject obj = (SearchResultObject) arg1;
                if(obj.data == null){
                    lvSearchData.setVisibility(View.GONE);
                    lvdata.setVisibility(View.VISIBLE);
                    return;
                }
                if(poiResultAdapter ==null){
                    poiResultAdapter = new PoiResultAdapter(obj.data,getContext());
                    lvSearchData.setAdapter(poiResultAdapter);
                }else {
                    poiResultAdapter.setCarStatusData(obj.data);
                    poiResultAdapter.notifyDataSetChanged();
                }
                lvSearchData.setVisibility(View.VISIBLE);
                lvdata.setVisibility(View.GONE);
                poiResultAdapter.setListener(new MyItemLongClickListener() {
                    @Override
                    public void onItemLongClick(View view, int postion) {
                        SearchResultObject.SearchResultData obj ;
                        List<AddressBean> addressList= AddressHistoryUtils.getAddressHistoty();
                        obj = poiResultAdapter.getCarStatusData().get(postion);
                        //保存搜索记录
                        addressBean = new AddressBean();
                        addressBean.setName(obj.title);
                        addressBean.setAddress(obj.address);
                        addressBean.setLatitude(obj.location.lat);
                        addressBean.setLongitude(obj.location.lng);
                        if(addressList==null){
                            addressList = new ArrayList<>();
                        }
                        addressList.add(addressBean);
                        AddressHistoryUtils.saveAddressHistory(addressList);

                        et_search.removeTextChangedListener(textWatcher);
                        CharSequence cs = ((TextView)view.findViewById(R.id.tv_map_result_address)).getText();
                        et_search.setText(cs);
                        et_search.setSelection(et_search.getText().length());
                        lvSearchData.setVisibility(View.GONE);
                        et_search.addTextChangedListener(textWatcher);
                        Intent intent = Router.fromPath(MapActivityConst.Path.MAP_SEND_CAR);
                        if(flg.equals("modifyhome")){
                            intent.putExtra("set","sethome");
                        }else if(flg.equals("modifycompany")){
                            intent.putExtra("set","setcompany");
                        } else {
                            intent.putExtra("set","send");
                        }
                        intent.putExtra("addresslat",obj.location.lat+"");
                        intent.putExtra("addresslng",obj.location.lng+"");
                        intent.putExtra("title",obj.title);
                        intent.putExtra("address",obj.address);
                        ActivityUtils.startActivity(getActivity(),intent);
                    }
                });
                String result = "搜索poi\n";
                for(SearchResultObject.SearchResultData data : obj.data){
//                    Log.v("SearchDemo","title:"+data.title + ";" + data.address);
//                    result += data.address+"\n";
                }
//                printResult(result);
            }
        });
    }

    @Override
    protected IMapPresenter createPresenter() {
        return new MapPresenter();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        final Activity activity = getActivity();
        if (i == R.id.et_map_to_search) {
            if(!et_search.hasFocus()){
                lvSearchData.setVisibility(View.GONE);
                lvdata.setVisibility(View.VISIBLE);
            }
        }else if(i==R.id.iv_map_search_close){
            et_search.setText("");
                lvSearchData.setVisibility(View.VISIBLE);
                lvdata.setVisibility(View.GONE);
        }else if (i == R.id.iv_map_search_glass) {
//            Intent intent = Router.fromPath(MapActivityConst.Path.MAP_MENU_RESULT);
//            intent.putExtra("menu",et_search.getText().toString());
//            ActivityUtils.startActivity(activity,intent);
            getActivity().finish();
        }else if (i == R.id.tv_map_search_collect) {
            Intent inent = Router.fromPath(MapActivityConst.Path.MAP_TO_COLLECT);
            ActivityUtils.startActivity(activity,inent);
        }else if (i == R.id.ll_map_home_address) {
            if(tvhome.getText().toString().equals("去设置")){
                Intent intent = Router.fromPath(MapActivityConst.Path.MAP_TO_SEARCH);
                intent.putExtra("set","sethome");
                ActivityUtils.startActivity(activity,intent);
            }else {
                if(homeAddress!=null){
                    Intent intent = Router.fromPath(MapActivityConst.Path.MAP_SEND_CAR);
                    intent.putExtra("set","send");
                    intent.putExtra("addresslat",homeAddress.getLatitude()+"");
                    intent.putExtra("addresslng",homeAddress.getLongitude()+"");
                    intent.putExtra("title",homeAddress.getName());
                    intent.putExtra("address",homeAddress.getAddress());
                    ActivityUtils.startActivity(activity, intent);
                }
            }
        }else if (i == R.id.ll_map_company_address) {
            if(tvcompany.getText().toString().equals("去设置")){
                Intent intent = Router.fromPath(MapActivityConst.Path.MAP_TO_SEARCH);
                intent.putExtra("set","setcompany");
                ActivityUtils.startActivity(activity,intent);
            }else {
                if(companyAddress!=null){
                    Intent intent = Router.fromPath(MapActivityConst.Path.MAP_SEND_CAR);
                    intent.putExtra("set","send");
                    intent.putExtra("addresslat",companyAddress.getLatitude()+"");
                    intent.putExtra("addresslng",companyAddress.getLongitude()+"");
                    intent.putExtra("title",companyAddress.getName());
                    intent.putExtra("address",companyAddress.getAddress());
                    ActivityUtils.startActivity(activity, intent);
                }
            }
        }else if (i == R.id.tv_map_search_gasstation) {
            Intent intent = Router.fromPath(MapActivityConst.Path.MAP_MENU_RESULT);
            intent.putExtra("menu","one");
            ActivityUtils.startActivity(activity,intent);
        }else if (i == R.id.tv_map_search_charge) {
            Intent intent = Router.fromPath(MapActivityConst.Path.MAP_MENU_RESULT);
            intent.putExtra("menu","two");
            ActivityUtils.startActivity(activity,intent);
        }else if (i == R.id.tv_map_search_cate) {
            Intent intent = Router.fromPath(MapActivityConst.Path.MAP_MENU_RESULT);
            intent.putExtra("menu","three");
            ActivityUtils.startActivity(activity,intent);
        }else if (i == R.id.tv_map_search_hotel) {
            Intent intent = Router.fromPath(MapActivityConst.Path.MAP_MENU_RESULT);
            intent.putExtra("menu","four");
            ActivityUtils.startActivity(activity,intent);
        }else if(i==R.id.iv_map_search_go_back){
            getActivity().finish();
        }
    }

    @Override
    public void getMapCollected(BaseResponse<MapCollectedResponse> response) {

    }

    @Override
    public void addMapCollected(BaseResponse<BaseResponse> response) {

    }

    @Override
    public void deleteMapCollected(BaseResponse<BaseResponse> response) {
        DialogUtils.showToast(getActivity(),response.getMsg());
    }

    @Override
    public void mapHomeCompany(BaseResponse<MapHomeCompanyResponse> response) {
        int code = response.getCode();
        if(code==0){
            if(response.getData().getHomeAddress()!=null){
                if(!TextUtils.isEmpty(response.getData().getHomeAddress().getAddress())){
                    homeAddress = new AddressBean();
                    homeAddress=response.getData().getHomeAddress();
                    homeAddress.setLatitude(response.getData().getHomeAddress().getLatitude());
                    homeAddress.setLongitude(response.getData().getHomeAddress().getLongitude());
                    homeAddress.setName(response.getData().getHomeAddress().getName());
                    homeAddress.setAddress(response.getData().getHomeAddress().getAddress());
                    tvhome.setText(response.getData().getHomeAddress().getAddress());
                }
            }
            if(response.getData().getCompanyAddrss()!=null) {
                if (!TextUtils.isEmpty(response.getData().getCompanyAddrss().getAddress())) {
                    tvcompany.setText(response.getData().getCompanyAddrss().getAddress());
                    companyAddress = new AddressBean();
                    companyAddress.setLatitude(response.getData().getCompanyAddrss().getLatitude());
                    companyAddress.setLongitude(response.getData().getCompanyAddrss().getLongitude());
                    companyAddress.setName(response.getData().getCompanyAddrss().getName());
                    companyAddress.setAddress(response.getData().getCompanyAddrss().getAddress());
                    tvcompany.setText(response.getData().getCompanyAddrss().getAddress());
                }
            }
        }
    }

    @Override
    public void mapSendToCar(BaseResponse<MapHomeCompanyResponse> response) {

    }

    @Override
    public void getLastLocation(BaseResponse<MapCarLocation> response) {

    }

    @Override
    public void updateLocation(BaseResponse<MapCarLocation> response) {

    }


    @Override
    public void onStart() {
        super.onStart();
        // 获取意图对象获取传递的值
        Intent intent = getActivity().getIntent();
        flg = intent.getStringExtra("set");
        if(TextUtils.isEmpty(flg)){
            flg="set";
        }
        Log.e("eee",flg+"---");
        din=TXSharedPreferencesUtils.getValue("car_activate_info");
        if(!TextUtils.isEmpty(din)) {
            getPresenter().getHomeAddress(din);
        }else {
            getPresenter().getHomeAddress("");
        }
//        listAddress = AddressHistoryUtils.getAddressHistoty();
//        if(listAddress==null){
//            lvdata.setVisibility(View.GONE);
//        } else{
//            lvdata.setVisibility(View.VISIBLE);
//            Collections.reverse(listAddress);
//            searchResultAdapter=new InventoryAdapter(getContext(),listAddress);
//            //点击查看
//            searchResultAdapter.setItemClickLister(new InventoryAdapter.OnItemClickLister() {
//                @Override
//                public void onItemClickLister(View view, int position) {
//                    Intent intent = Router.fromPath(MapActivityConst.Path.MAP_SEND_CAR);
//                    if(flg.equals("modifyhome")){
//                        intent.putExtra("set","sethome");
//                    }else if(flg.equals("modifycompany")){
//                        intent.putExtra("set","setcompany");
//                    } else {
//                        intent.putExtra("set","send");
//                    }
//                    intent.putExtra("addresslat",listAddress.get(position).getLatitude()+"");
//                    intent.putExtra("addresslng",listAddress.get(position).getLongitude()+"");
//                    intent.putExtra("title",listAddress.get(position).getName());
//                    intent.putExtra("address",listAddress.get(position).getAddress());
//                    ActivityUtils.startActivity(getActivity(),intent);
//                }
//            });
//            //删除操作
//            searchResultAdapter.setOnDeleteClickListener(new InventoryAdapter.OnDeleteClickLister() {
//                @Override
//                public void onDeleteClick(View view, int position) {
//                    listAddress.remove(position);
//                    AddressHistoryUtils.saveAddressHistory(listAddress);
//                    searchResultAdapter.notifyDataSetChanged();
//                    lvdata.closeMenu();
//                }
//            });
//            lvdata.setAdapter(searchResultAdapter);
//        }
        et_search.addTextChangedListener(textWatcher);
    }

    @Override
    public void onResume() {
        super.onResume();


    }

    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    public void onStop() {
        super.onStop();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
